package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.RadioGroup;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.WarehouseAreaListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean2.warehouse.OpenCity;
import com.wuliupai.delivery.wuliupaidelivery.bean2.warehouse.OpenCityListResult;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.fragment.OrderPickUpFragment_;
import com.wuliupai.delivery.wuliupaidelivery.fragment.OrderSendFragment_;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_order_list)
public class GrabOrderListActivity extends AppBaseActivity {

    @ViewById(R.id.rg_orderTab)
    RadioGroup rg_orderTab;

    private GrabOrderListActivity _activity;

    private FragmentManager mFragmentManager;
    private OrderPickUpFragment_ mDispatchFragment;
    private OrderSendFragment_ mTransportFragment;

    private final int FragmentType_PickUpList = 0; // 揽收
    private final int FragmentType_SendList = 1; // 派送

    private MenuItem menuItem1;
    private List<OpenCity> dataList = new ArrayList<>();
    private String cityCurrent = ""; // 当前城市

    private LocalBroadcastManager lbm = null;
    public LocationClient mLocationClient = null;
    private BDLocationListener myListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            mLocationClient.stop();
            cityCurrent = bdLocation.getCity();
            updateCityAndSendBroadcast();
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BroadcastChannels.Channel_GrabOrderSuccess: // 抢单成功
                    finish();
                    animUtils.leftOutAnimation(_activity);
                    break;
            }
        }
    };

    @AfterViews
    void onPageStart() {
        _activity = this;

        lbm = LocalBroadcastManager.getInstance(_activity);

        registerMyReceiver();

        setTitle(this, R.string.string_orderList_title, R.drawable.comm_press_return_selector, true, new OnNavigationBtnClickListener() {
            @Override
            public void navigationClick() {
                finish();
                animUtils.leftOutAnimation(_activity);
            }

            @Override
            public void menuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menuItem1:
                        showWarehouseAreaDialog();
                        break;
                }
            }
        });
        initFragment();

        rg_orderTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_pickUpTab:
                        showFragment(FragmentType_PickUpList);
                        break;

                    case R.id.rb_sendTab:
                        showFragment(FragmentType_SendList);
                        break;
                }
            }
        });

        initAndStartLocation();
        getOpenCity();
    }

    private void registerMyReceiver() {
        IntentFilter filter = new IntentFilter(BroadcastChannels.Channel_GrabOrderSuccess);
        lbm.registerReceiver(receiver,filter);
    }

    /**
     * 显示城市切换的对话框
     */
    private void showWarehouseAreaDialog() {
        Dialog dialog = new Dialog(_activity, R.style.DialogFullWindowStyle);// 创建自定义样式dialog

        dialog.setCancelable(false);// 不可以用“返回键”取消
        dialog.setContentView(R.layout.dialog_warehouse_area_list);// 设置布局

        ListView lv_warehouseArea = (ListView) dialog.findViewById(R.id.lv_warehouseArea);


        WarehouseAreaListAdapter adapter = new WarehouseAreaListAdapter(_activity, dataList);
        lv_warehouseArea.setAdapter(adapter);

        lv_warehouseArea.setOnItemClickListener((parent, view, position, id) -> {

            String citySelect = dataList.get(position).getcName();
            if (!cityCurrent.equals(citySelect)) {
                cityCurrent = citySelect;
                updateCityAndSendBroadcast();
            }
            dialog.dismiss();
        });

        dialog.findViewById(R.id.ivBtn_closeDialog).setOnClickListener(v ->
                dialog.dismiss());
        dialog.show();
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        mFragmentManager = getFragmentManager();
        mDispatchFragment = (OrderPickUpFragment_) mFragmentManager.findFragmentByTag(OrderPickUpFragment_.class.getName());
        if (null == mDispatchFragment) {
            mDispatchFragment = new OrderPickUpFragment_();
            mFragmentManager.beginTransaction().add(R.id.fl_fragmentHolder, mDispatchFragment, OrderPickUpFragment_.class.getName()).commit();
        }

        mTransportFragment = (OrderSendFragment_) mFragmentManager.findFragmentByTag(OrderSendFragment_.class.getName());
        if (null == mTransportFragment) {
            mTransportFragment = new OrderSendFragment_();
            mFragmentManager.beginTransaction().add(R.id.fl_fragmentHolder, mTransportFragment, OrderSendFragment_.class.getName()).commit();
        }
        showFragment(FragmentType_PickUpList);
    }

    /**
     * 标签切换
     *
     * @param index
     */
    public void showFragment(int index) {
        if (null == mDispatchFragment) {
            mDispatchFragment = new OrderPickUpFragment_();
        }
        if (null == mTransportFragment) {
            mTransportFragment = new OrderSendFragment_();
        }
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

        switch (index) {
            case FragmentType_PickUpList:
                hideAll();
                fragmentTransaction.show(mDispatchFragment).commitAllowingStateLoss();
                break;

            case FragmentType_SendList:
                hideAll();
                fragmentTransaction.show(mTransportFragment).commitAllowingStateLoss();
                break;
        }
    }

    /**
     * 隐藏所有的Fragment
     */
    private void hideAll() {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.hide(mDispatchFragment).hide(mTransportFragment).commitAllowingStateLoss();
    }

    /**
     * 设置当前城市并发送广播
     */
    private void updateCityAndSendBroadcast() {
        menuItem1.setVisible(true).setTitle(cityCurrent);
        sendRefreshBroadcast(cityCurrent);
    }

    /**
     * 发送刷新页面的广播
     *
     * @param city
     */
    private void sendRefreshBroadcast(String city) {
        Intent intent = new Intent();
        intent.putExtra("area", city);
        intent.setAction(BroadcastChannels.Channel_RefreshOrderListByArea);
        lbm.sendBroadcast(intent);
    }

    /**
     * 初始化并开始定位
     */
    private void initAndStartLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedLocationDescribe(true); // 可选，是否需要位置描述信息，默认为不需要，即参数为false
        mLocationClient.setLocOption(option);
        mLocationClient.registerLocationListener(myListener);
        mLocationClient.start();
    }

    /**
     * 获取仓库开通城市的列表
     */
    public void getOpenCity() {
        OpenCity bean = new OpenCity();
        String jsonOrderDetail = JsonUtils.createJsonString(bean);
        try {
            String aesOrderDetail = JsonUtils.aes(jsonOrderDetail);
            callNet(this, InterfaceNet.Net_GetWarehouseAreaList, aesOrderDetail, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {

                    if (!StringUtils.isEmpty(content)) {
                        try {

                            OpenCityListResult result = (OpenCityListResult) JsonUtils.parseJsonString(content, OpenCityListResult.class);
                            dataList.addAll(result.getInfolist());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menuItem1 = menu.findItem(R.id.menuItem1);
        menuItem1.setVisible(false);
        menu.findItem(R.id.menuItem2).setVisible(false);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        unregisterMyReceiver(lbm,receiver);
    }
}
